import {
	http_mpWeixinRegisterAndLogin,
	http_mpToutiaoRegisterAndLogin,
	http_logout,
	http_syncLikeAndSave,
	http_jssdkConfig,
} from '@/common/api.js';

// #ifdef H5
var jweixin = require('jweixin-module')
// #endif

import config from '@/common/config.js';

export default {
	data() {
		return {
			cosUrl: 'https://ykx-1254116920.cos.ap-nanjing.myqcloud.com',
			scrollNum: 0,

			shareTitle: '成都亚克茜科技',
			shareDesc: '用互联网技术服务企业，在互联网的媒体中建立一条企业和客户的沟通桥梁',
			share5v4Image: 'https://ykx-1254116920.cos.ap-nanjing.myqcloud.com/bg/shareimage_homepage_5v4.png',
			share1v1Image: 'https://ykx-1254116920.cos.ap-nanjing.myqcloud.com/bg/logo.png',
		}
	},
	onPageScroll(e) {
		this.scrollNum = e.scrollTop
	},
	// 页面栈   最多10层
	async onShow() {
		// #ifdef MP-WEIXIN
		if (process.env.NODE_ENV == 'development') {
			const RT = getCurrentPages();
			const ROUTERLn = RT.map(e => e.route)
			switch (ROUTERLn.length) {
				case 10:
					console.log('routers:', ROUTERLn);
					console.warn('已经到达路由上限');
					break;
				case 9:
					console.log('routers:', ROUTERLn);
					console.error('即将到达路由上限');
					break;
				default:
					console.log('routers:', ROUTERLn);
			}
		}
		// #endif

		// #ifdef H5
		this.share()
		// #endif

	},
	onLoad() {
		console.log('hahahahah')



	},
	onShareAppMessage() {
		return {
			'title': this.shareTitle,
			'imageUrl': this.share5v4Image,
		}
	},
	onShareTimeline() {
		return {
			'title': this.shareTitle,
			'imageUrl': this.share1v1Image,
		}
	},
	methods: {
		// #ifdef H5
		share() {
			let url = window.location.href
			let that = this
			http_jssdkConfig({
				url: url,
				api_list: ['updateAppMessageShareData', 'updateTimelineShareData'].join("-")
			}).then(res => {
				// console.log(res);
				let data = res.data
				if (res.code) {
					jweixin.config({
						debug: false,
						appId: data.appId,
						timestamp: data.timestamp,
						nonceStr: data.nonceStr,
						signature: data.signature,
						jsApiList: data.jsApiList,
					});
					jweixin.ready(function() {
						var shareData = {
							title: that.shareTitle,
							desc: that.shareDesc,
							link: url,
							imgUrl: that.share1v1Image,
							success: function(res) {
								console.log(res);
							},
							cancel: function(res) {}
						};

						//分享给朋友接口  
						jweixin.updateAppMessageShareData(shareData);

						//分享到朋友圈接口  
						jweixin.updateTimelineShareData(shareData);
					})
					jweixin.error(function(res) {
						// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
						console.log('anything wrong');
						console.log(res);
					})
				}
			})

		},
		// #endif

		//节流  点赞相关
		d_toggleLikeblog_throttle(id) {
			this.$u.throttle(() => this.d_toggleLikeblog(id))
		},
		d_toggleSaveblog_throttle(id) {
			this.$u.throttle(() => this.d_toggleSaveblog(id))
		},
		d_toggleLikeexample_throttle(id) {
			this.$u.throttle(() => this.d_toggleLikeexample(id))
		},
		d_toggleSaveexample_throttle(id) {
			this.$u.throttle(() => this.d_toggleSaveexample(id))
		},
		toggleLikeexample_throttle(v) {
			this.$u.throttle(() => this.toggleLikeexample(v))
		},
		toggleSaveexample_throttle(v) {
			this.$u.throttle(() => this.toggleSaveexample(v))
		},
		toggleLikeblog_throttle(v) {
			this.$u.throttle(() => this.toggleLikeblog(v))
		},
		toggleSaveblog_throttle(v) {
			this.$u.throttle(() => this.toggleSaveblog(v))
		},


		d_toggleLikeexample(id) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_likeexample.includes(id)) {
				this.vuex_likeexample.splice(this.vuex_likeexample.indexOf(id), 1)
				this.vuex_synclikeexample(this.vuex_likeexample)
				act = 'sub'
			} else {
				this.vuex_likeexample.push(id)
				this.vuex_synclikeexample(this.vuex_likeexample)
				act = 'add'
			}

			http_syncLikeAndSave({
				field: 'likeexample',
				value: this.vuex_likeexample,
				item_id: id,
				action: act
			})
		},
		d_toggleSaveexample(id) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_saveexample.includes(id)) {
				this.vuex_saveexample.splice(this.vuex_saveexample.indexOf(id), 1)
				this.vuex_syncsaveexample(this.vuex_saveexample)
				act = 'sub'
			} else {
				this.vuex_saveexample.push(id)
				this.vuex_syncsaveexample(this.vuex_saveexample)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'saveexample',
				value: this.vuex_saveexample,
				item_id: id,
				action: act
			})
		},
		d_toggleLikeblog(id) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_likeblog.includes(id)) {
				this.vuex_likeblog.splice(this.vuex_likeblog.indexOf(id), 1)
				this.vuex_synclikeblog(this.vuex_likeblog)
				act = 'sub'
			} else {
				this.vuex_likeblog.push(id)
				this.vuex_synclikeblog(this.vuex_likeblog)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'likeblog',
				value: this.vuex_likeblog,
				item_id: id,
				action: act
			})
		},
		d_toggleSaveblog(id) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_saveblog.includes(id)) {
				this.vuex_saveblog.splice(this.vuex_saveblog.indexOf(id), 1)
				this.vuex_syncsaveblog(this.vuex_saveblog)
				act = 'sub'
			} else {
				this.vuex_saveblog.push(id)
				this.vuex_syncsaveblog(this.vuex_saveblog)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'saveblog',
				value: this.vuex_saveblog,
				item_id: id,
				action: act
			})
		},
		jumpGO(url) {
			uni.navigateTo({
				url: `/pages/${url}`
			})
		},
		toggleLikeexample(v) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_likeexample.includes(v.id)) {
				v.likecount = v.likecount - 1
				this.vuex_likeexample.splice(this.vuex_likeexample.indexOf(v.id), 1)
				this.vuex_synclikeexample(this.vuex_likeexample)
				act = 'sub'
			} else {
				v.likecount = v.likecount + 1
				this.vuex_likeexample.push(v.id)
				this.vuex_synclikeexample(this.vuex_likeexample)
				act = 'add'
			}

			http_syncLikeAndSave({
				field: 'likeexample',
				value: this.vuex_likeexample,
				item_id: v.id,
				action: act
			})
		},
		toggleSaveexample(v) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_saveexample.includes(v.id)) {
				v.savecount = v.savecount - 1
				this.vuex_saveexample.splice(this.vuex_saveexample.indexOf(v.id), 1)
				this.vuex_syncsaveexample(this.vuex_saveexample)
				act = 'sub'
			} else {
				v.savecount = v.savecount + 1
				this.vuex_saveexample.push(v.id)
				this.vuex_syncsaveexample(this.vuex_saveexample)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'saveexample',
				value: this.vuex_saveexample,
				item_id: v.id,
				action: act
			})
		},
		toggleLikeblog(v) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_likeblog.includes(v.id)) {
				v.likecount = v.likecount - 1
				this.vuex_likeblog.splice(this.vuex_likeblog.indexOf(v.id), 1)
				this.vuex_synclikeblog(this.vuex_likeblog)
				act = 'sub'
			} else {
				v.likecount = v.likecount + 1
				this.vuex_likeblog.push(v.id)
				this.vuex_synclikeblog(this.vuex_likeblog)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'likeblog',
				value: this.vuex_likeblog,
				item_id: v.id,
				action: act
			})
		},
		toggleSaveblog(v) {
			if (!this.vuex_has_login) {
				uni.showToast({
					title: '请先登录，再操作',
					icon: 'none',
					duration: 2000,
				});
				return
			}
			var act = ''
			if (this.vuex_saveblog.includes(v.id)) {
				v.savecount = v.savecount - 1
				this.vuex_saveblog.splice(this.vuex_saveblog.indexOf(v.id), 1)
				this.vuex_syncsaveblog(this.vuex_saveblog)
				act = 'sub'
			} else {
				v.savecount = v.savecount + 1
				this.vuex_saveblog.push(v.id)
				this.vuex_syncsaveblog(this.vuex_saveblog)
				act = 'add'
			}
			http_syncLikeAndSave({
				field: 'saveblog',
				value: this.vuex_saveblog,
				item_id: v.id,
				action: act
			})
		},
		goTop() {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 50
			})
		},
		jumpBlogDetail(v) {
			var url = ''
			if (1 == v.sharetype.id) {
				url = `/pages/website/video?id=${v.id}`
			} else {
				url = `/pages/website/shareDetail?id=${v.id}`
			}

			uni.navigateTo({
				url: url
			})
		},
		gotoExamplelistPage(v) {
			let url = `/pages/website/casePresentation?t=${v.t}&name=${v.name}&id=${v.id}`

			uni.navigateTo({
				url: url
			})
		},
		distance(lat1, lng1, lat2, lng2) {
			lat1 = parseFloat(lat1)
			lng1 = parseFloat(lng1)
			lat2 = parseFloat(lat2)
			lng2 = parseFloat(lng2)

			var radLat1 = lat1 * Math.PI / 180.0;
			var radLat2 = lat2 * Math.PI / 180.0;
			var a = radLat1 - radLat2;
			var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
				Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137; // EARTH_RADIUS;
			s = Math.round(s * 10000) / 10000;

			s = s * 1000

			if (isNaN(s)) {
				return 0 + 'm';
			}

			if (s > 1000) {
				//    大于1000米时
				s = Math.floor(s / 1000 * 100) / 100;
				s = s + '公里'
			} else {
				//    小于1000米直接返回
				s = s.toFixed(2) + '米'
			}

			return s;
		},
		doAfterLogin(f) {
			if (!this.vuex_has_login) {
				uni.showLoading({
					title: '加载中'
				});
				let data = {}
				new Promise((resolve, reject) => {
					uni.getUserProfile({
						desc: "得到用户个人信息用于登录",
						lang: 'zh_CN',
						success: (res) => {
							// console.log(res);
							data.nickname = res.userInfo.nickName
							data.gender = res.userInfo.gender
							data.avatar = res.userInfo.avatarUrl
							resolve()
						},
						fail: (err) => {
							reject(err)
						},
					})
				}).then(() => {
					return new Promise((resolve, reject) => {
						// #ifdef MP-WEIXIN
						uni.login({
							provider: 'weixin',
							success: (res) => {
								data.code = res.code
								resolve()
							},
							fail: (err) => {
								reject(err)
							},
						})
						// #endif
						// #ifdef MP-TOUTIAO
						tt.login({
							force: true,
							success(res) {
								data.code = res.code
								resolve()
							},
							fail(res) {
								reject(err)
							},
						});
						// #endif

					})

				}).then(() => {
					// #ifdef MP-WEIXIN
					http_mpWeixinRegisterAndLogin(data)
						.then((res) => {
							console.log(res);
							this.$u.toast(res.msg, 2000)
							if (1 == res.code) {
								this.vuex_login(res)
								this.vuex_synclikeexample(res.data.userinfo
									.likeexample) // 在登录时同步用户对blog和case的收藏信息
								this.vuex_syncsaveexample(res.data.userinfo.saveexample)
								this.vuex_synclikeblog(res.data.userinfo.likeblog)
								this.vuex_syncsaveblog(res.data.userinfo.saveblog)
							}
							uni.hideLoading()
						})
						.then(() => {
							f()
						})
					// #endif
					// #ifdef MP-TOUTIAO
					http_mpToutiaoRegisterAndLogin(data)
						.then((res) => {
							console.log(res);
							this.$u.toast(res.msg, 2000)
							if (1 == res.code) {
								this.vuex_login(res)
								this.vuex_synclikeexample(res.data.userinfo
									.likeexample) // 在登录时同步用户对blog和case的收藏信息
								this.vuex_syncsaveexample(res.data.userinfo.saveexample)
								this.vuex_synclikeblog(res.data.userinfo.likeblog)
								this.vuex_syncsaveblog(res.data.userinfo.saveblog)
							}
							uni.hideLoading()
						})
						.then(() => {
							f()
						})
					// #endif

				}).catch((e) => {
					uni.hideLoading()
					console.log(e);
				})
			} else {
				f()
			}
		},

		weblogin() {
			// #ifdef H5
			if (this.$util.isWechatBrowser()) {
				let appid = config.gzh_appid;
				let uri = encodeURIComponent(window.location.href);
				let authURL =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
				window.location.href = authURL;
			} else {
				uni.showToast({
					title: '请使用在微信里，用微信浏览器登录',
					icon: 'none',
				})
			}
			// #endif

			return
		},

		wx_login() {
			this.doAfterLogin(() => {
				// 当时做用户socket聊天时加的
				// const userID = this.vuex_user.username
				// const userSig = this.vuex_user.chat_usersig
			})
		},

		logout() {
			http_logout()
				.then(res => {
					if (1 == res.code) {
						this.vuex_logout()
					} else {
						this.$u.toast('退出失败，请联系管理员', 2000)
					}
				})
		},

		/*工具函数*/
		strSub(str, len) {
			if (str) {
				if (str.length > len) {
					return str.substr(0, len) + '\n' + this.strSub(str.substr(len), len)
				} else {
					let reason = str
					return reason
				}
			}
			return str
		},


	}
}